package com.parkinglot.service.Impl;

import com.github.wxpay.sdk.WXPayUtil;
import com.parkinglot.core.PayUtil;
import com.parkinglot.core.Result;
import com.parkinglot.parmeter.OrderPayParm;
import com.parkinglot.pojo.Order;
import com.parkinglot.pojo.WechatPay;
import com.parkinglot.service.OrderService;
import com.parkinglot.service.WechatPayService;
import com.parkinglot.util.DateUtils;
import com.parkinglot.util.HttpTools;
import com.parkinglot.util.HttpUrlutils;
import com.parkinglot.vo.OrderqueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class WechatPayServiceImpl implements WechatPayService {
    @Resource
    private OrderService orderService;
    @Resource
    private HttpUrlutils httpUrlutils;
    /**
     * 停车场扫码预付款
     * @return
     */
    @Override
    public Map<String,String> yufuuan(OrderPayParm orderPayParm)throws Exception {
        BigDecimal big=new BigDecimal(0.01);
        log.info(orderPayParm.toString());
        //查询订单
        Order order = new Order();
        order.setUserid(orderPayParm.getUserid());
        order.setCarnumber(orderPayParm.getCarnumber());
        order.setGarageid(orderPayParm.getGarageid());
        OrderqueryVo orderqueryVo = orderService.queryOrder(order);

        if (orderqueryVo != null && null != orderqueryVo.getOrdernumber() ) {

            //拼接下单地址参数
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("appid", WechatPay.getAppId());
            paraMap.put("mch_id", WechatPay.getMch_id());
            paraMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paraMap.put("out_trade_no", orderqueryVo.getOrdernumber());
            paraMap.put("openid", orderPayParm.getUserid());
            paraMap.put("total_fee",String.valueOf(big.multiply(new BigDecimal(100)).intValue()));//单位为分
            paraMap.put("spbill_create_ip", "123.12.12.123");
            paraMap.put("notify_url", "http://47.104.250.83/parking/pay/yufukuanNotify");
            paraMap.put("trade_type", "JSAPI");
            paraMap.put("body", "测试微信支付");
            String sign = WXPayUtil.generateSignature(paraMap, WechatPay.getKey());
            paraMap.put("sign", sign);
            String xml = WXPayUtil.mapToXml(paraMap);
            String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            Map<String, String> mapHeader = new HashMap<String, String>();
            mapHeader.put("Content-Type", "application/json;charset=utf-8");
            String xmlStr = HttpTools.post(unifiedorder_url, xml, mapHeader);
            System.out.println("调取微信支付返回的值：" + xmlStr);
            if (xmlStr.indexOf("SUCCESS") != -1) {
                Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
                Map<String, String> reData = new HashMap<>();
                reData.put("appId", WechatPay.getAppId());
                reData.put("nonceStr", map.get("nonce_str"));
                String newPackage = "prepay_id=" + map.get("prepay_id");
                reData.put("package", newPackage);
                reData.put("signType", "MD5");
                reData.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
                String newSign = WXPayUtil.generateSignature(reData, WechatPay.getKey());
                map.put("paySign", newSign);
                map.put("timeStamp", reData.get("timeStamp"));
                log.info("时间:" + DateUtils.getFormatDate(new Date()) + ":openid:" + orderPayParm.getUserid() + "发起支付请求,支付金额:" + String.valueOf(orderqueryVo.getPayMoney().multiply(new BigDecimal(100)).intValue()) + "停车场编号" + orderPayParm.getGarageid());
                return map;
            }
        }
        return null;

    }

    @Override
    public Result yufukuanNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{

        log.info("调用微信预付款支付回调");
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        log.debug(sb.toString());
        //sb为微信返回的xml
        String resXml = "";
        //解析微信返回的xml串
        Map map = PayUtil.doXMLParse(sb.toString());

        String returnCode = (String) map.get("return_code");

        if ("SUCCESS".equals(returnCode)) {
            log.info("进入了回调，并修改支付状态");
            String oredernumber = map.get("out_trade_no").toString();
            OrderqueryVo orderqueryVo = orderService.queryByordernum(oredernumber);
            if (orderqueryVo != null) {
                Order order = new Order();
                order.setPayStatus("1");
                order.setPayTime(DateUtils.getFormatDate(new Date()));
                order.setOrdernumber(orderqueryVo.getOrdernumber());
                order.setParkingCktime(DateUtils.getFormatDate(new Date()));
                order.setParkingTime(DateUtils.getFormatDate(new Date(new Date().getTime()+15*60*1000)));
                orderService.update(order);
                String tgurl = "http://192.168.3.205:8080/inPark/unlicensedInPark?carNumber=" + oredernumber + "&parkId=" + orderqueryVo.getGarageid();
                Map<String, Object> maps = httpUrlutils.getresult(tgurl);
                log.info("订单编号："+oredernumber+":openid:"+orderqueryVo.getUserid()+",支付金额："+orderqueryVo.getPayMoney()+",支付状态:"+orderqueryVo.getPayStatus());

            }

            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();

        return Result.success(resXml);
    }


}
